package com.example.linearlayoutdemo;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookViewHolder> {
    private List<Book> mBookList;
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        void onItemClick(Book book);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    public void setBookList(List<Book> bookList) {
        mBookList = bookList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_book, parent, false);
        return new BookViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BookViewHolder holder, int position) {
        if (mBookList == null) return;
        Book book = mBookList.get(position);
        holder.tvBookNumber.setText("书号：" + book.getBookNumber());
        holder.tvBookName.setText("书名：" + book.getBookName());

        holder.itemView.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onItemClick(book);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mBookList == null ? 0 : mBookList.size();
    }

    static class BookViewHolder extends RecyclerView.ViewHolder {
        TextView tvBookNumber;
        TextView tvBookName;

        public BookViewHolder(View itemView) {
            super(itemView);
            tvBookNumber = itemView.findViewById(R.id.tv_book_number);
            tvBookName = itemView.findViewById(R.id.tv_book_name);
        }
    }
}
    